package com.zhuiyun.educations.api.newCourse.mapper;

/**
 * @ClassName SolveSudoku
 * @Description TODO
 * @Author 杨友朋
 * @Date 2023/7/6 20:22
 **/
public class SolveSudoku {
    public static void main(String[] args) {
        int[][] board = {
                {0, 0, 0, 0, 9, 0, 0, 0, 1},
                {1, 0, 3, 0, 8, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 8, 3, 0},
                {0, 4, 0, 0, 1, 8, 0, 0, 0},
                {0, 0, 0, 0, 3, 0, 0, 0, 0},
                {0, 0, 6, 0, 5, 0, 0, 0, 0},
                {0, 0, 0, 0, 7, 0, 0, 0, 0},
                {0, 1, 4, 8, 0, 9, 0, 0, 2},
                {0, 0, 0, 0, 0, 0, 1, 0, 0}
        };

        if (solveSudoku(board)) {
            printBoard(board);
        } else {
            System.out.println("出题错误,无解!!!");
        }
    }

    public static boolean solveSudoku(int[][] board) {
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                if (board[row][col] == 0) {
                    for (int num = 1; num <= 9; num++) {
                        if (isValid(board, row, col, num)) {
                            board[row][col] = num;
                            if (solveSudoku(board)) {
                                return true;
                            } else {
                                board[row][col] = 0; // 回溯
                            }
                        }
                    }
                    return false; // 所有数字都尝试过了，没有合适的解
                }
            }
        }
        return true; // 所有格子都被填充，找到解
    }

    public static boolean isValid(int[][] board, int row, int col, int num) {
        // 检查行是否合法
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == num) {
                return false;
            }
        }

        // 检查列是否合法
        for (int i = 0; i < 9; i++) {
            if (board[i][col] == num) {
                return false;
            }
        }

        // 检查3x3小方格是否合法
        int startRow = row - row % 3;
        int startCol = col - col % 3;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[startRow + i][startCol + j] == num) {
                    return false;
                }
            }
        }

        return true;
    }

    public static void printBoard(int[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }
}
